/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package systole.persistence.brokersDB;

import java.util.List;
import org.hibernate.Criteria;
import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import systole.domain.persons.identityCard.IdentityCardType;
import systole.exceptions.ExceptionDAO;
import systole.persistence.FacadeDB;
import systole.persistence.brokersInterface.IdentityCardBroker;

/**
 *
 * @author jmj
 */
public class IdentityCardBrokerDB extends BrokerDB implements IdentityCardBroker {

    /**
     * 
     */
    public IdentityCardBrokerDB() {
        super();
    }

    @Override
    public List<IdentityCardType> getAllIdentityCardTypes() throws ExceptionDAO {
        try {
            this.logger.logDebug("Getting Identities cards ");
            Session currentSession = FacadeDB.getInstance().getCurrentSession();
            @SuppressWarnings("unchecked")
            List<IdentityCardType> cardTypes = currentSession.createCriteria(IdentityCardType.class).addOrder(Order.asc("description")).list();
            this.logger.logDebug("Identities get successfully");
            return cardTypes;
        } catch (HibernateException e) {
            this.logger.logError("error on get Identities, msg: " + e.getMessage());
            throw new ExceptionDAO("No se pudieron obtener los tipos de documentos", e.fillInStackTrace());
        }
    }

    public void save(IdentityCardType cardType)throws ExceptionDAO{
         try {
            this.logger.logDebug("Saving Identity card ");
            Session currentSession = FacadeDB.getInstance().getCurrentSession();
            currentSession.save(cardType);
            this.logger.logDebug("save Identity card successfully");
        } catch (HibernateException e) {
            this.logger.logError("error on save Identity card, msg: " + e.getMessage());
            throw new ExceptionDAO("No se pudieron guardar los cambios", e.fillInStackTrace());
        }
    }


    public IdentityCardType getIdentityCardTypeByName(String description)throws ExceptionDAO {
        try {
            this.logger.logDebug("get IdentityCardType by name");
            Session currentSession = FacadeDB.getInstance().getCurrentSession();
            Criteria criteria = currentSession.createCriteria(IdentityCardType.class).
                    add(Restrictions.eq("description", description)).setMaxResults(1);
            return (IdentityCardType) criteria.uniqueResult();
        } catch (HibernateException e) {
            this.logger.logError("error on get IdentityCardType by name, msg: " + e.getMessage());
            throw new ExceptionDAO("No se pudo obtener los documentos", e.fillInStackTrace());
        }
    }

}
